/* begin: requestBuilder builds string for GET query. This string contains filter options and additional columns */
var	requestBuilder = function (oState, oSelf) {
    if ('' == window.location_search) {
        s = '?';
        for (var i in filter_options) {
            if (filter_options[i]) {
                if (!(i.indexOf('col_')==0)) {
                    s += 'filter_by_' + i + '=' + filter_options[i].replace(' ', '+').replace('&', '%26') + '&';
                } else {
                    s+=i.replace('&', '%26').replace(' ', '+')+'&';
                };
            };
        };
        return s;
    } else {
        ls = window.location_search;
        window.location_search = '';
        return ls;
    };
}
/* end: requestBuilder */


/* begin: Paginator */
var paginator = new YAHOO.widget.Paginator({rowsPerPage: RECORDS_PER_PAGE})

/* Change numbers of current showing records in paragraph "Showing ... of ..." */
paginator.subscribe('changeRequest', function(event) {
	var start_index = event.records[0] + 1;
	var end_index = event.records[1] + 1;
	jQuery('#records_index').text(start_index + '-' + end_index + ' of ');
	return true;
});

/* Change count of records in paragraph "Showing ... of ..." */
paginator.subscribe('beforeTotalRecordsChange', function(event) {
	var count = event.newValue;
	jQuery('#total_records').text(count);
	return true;
});
/* end: Paginator */


/* If we request page with params (e.g. whe user copy URL from 'Share') do initial load of data */
var initialLoad = false;
if (window.location_search != '') {
	initialLoad = true;
};

var ResultsDataTableDeferred = new YAHOO.widget.ScrollingDataTable(
	"results",
	ResultsColumnDefs,
	Results,
	{
		paginator: paginator,
		generateRequest: requestBuilder,
		width: "889px",
		initialLoad: initialLoad,
		initialRequest: requestBuilder(),
		MSG_EMPTY: emptyMessage
	}
);


/* begin: Table object */


with(Table=new Function){

	/* Reset table */
	prototype.reset=function(){

		var oState = ResultsDataTableDeferred.getState(), request, oCallback;
		var records = oState.pagination.records;
		var totalRecords = oState.pagination.totalRecords;
		request = ResultsDataTableDeferred.get("generateRequest")(oState, ResultsDataTableDeferred);            
		oCallback = {
			success : function(sRequest, oResponse, oPayload) {
				var r = oResponse;
				ResultsDataTableDeferred.onDataReturnInitializeTable(sRequest, oResponse, oPayload);
				jQuery("#img_loading").hide(); // Hide 'Loading' image (blue rolling circle)
				// Update count of records in paragraph "Showing ... of ..."
				var returned_results_count = oResponse.results.length;
				var end_index = RECORDS_PER_PAGE;
				if (returned_results_count<RECORDS_PER_PAGE) {
					end_index = returned_results_count;
				};
				jQuery('#records_index').text('1-' + end_index + ' of ');
				// Update filter options in paragraph "Showing ... of ..."
				update_filters_div();
			},
			failure : function(sRequest, oResponse, oPayload) {
				ResultsDataTableDeferred.onDataReturnInitializeTable(sRequest, oResponse, oPayload);
				jQuery("#img_loading").hide();
			},
			argument : oState,
			scope : ResultsDataTableDeferred
		}
		jQuery("#img_loading").show();
		Results.sendRequest(request, oCallback);
	};

	/* Reload a table, e.g. when user adds or removes column */
	prototype.reload=function(){
		var oState = ResultsDataTableDeferred.getState();
		var records = oState.pagination.records;
		var totalRecords = oState.pagination.totalRecords;
		request = ResultsDataTableDeferred.get("generateRequest")(oState, ResultsDataTableDeferred);
		oCallback = {
			success : function(sRequest, oResponse, oPayload) {
				ResultsDataTableDeferred.onDataReturnSetRows(sRequest, oResponse, oPayload);
				jQuery("#img_loading").hide();
			},
			failure : function(sRequest, oResponse, oPayload) {
				ResultsDataTableDeferred.onDataReturnSetRows(sRequest, oResponse, oPayload);
				jQuery("#img_loading").hide();
			},
			argument : oState,
			scope : ResultsDataTableDeferred
		};
		jQuery("#img_loading").show();
		Results.sendRequest(request, oCallback);
	};

	/* Construct HTML code of table for current results set  */
	prototype.view_as=function(v){
		switch(v) {
			case 'html':
				var recordSet = ResultsDataTableDeferred.getRecordSet();
				var columns = ResultsDataTableDeferred.getColumnSet().keys;
				var records = recordSet.getRecords();
				var l = recordSet.getLength();
				// Construct HTML code for table
				var timestamp = new Date().getTime();
				var table_html = '<p>&nbsp;</p>\n<table class="company_search_results" id="company_search_results_' + timestamp + '">\n\n<thead>\n\n<tr>\n';
				// Add column headers
				for (var i=0;i<columns.length;i++) {
					table_html += '<th>' + columns[i].label + '</th>';
				}
				table_html += '</tr>\n</thead>\n\n';
				// Add rows
				for (var i=0; i<l; i++) {
					table_html += "<tr>\n"
					for (var n=0;n<columns.length;n++) {
						table_html  += '\t<td valign="top">'
						d = recordSet.getRecord(i).getData(columns[n].key) || '&nbsp;'
						if (typeof(d)=='object') {
							var t = ''
							for (var k=0;k<d.length;k+=1) {
								if (d[k]) {
									t = t + '<li>' + d[k] + '</li>';

								};
							};
							table_html += '<ul>' + t + '</ul>';
						} else {
							table_html += d;
						};
						table_html += '</td>\n';
					};
					table_html += '</tr>\n\n';
				};
				table_html += '</table>';
				/* This is need for displaying table with Yahoo Interface in Analysis page */
				table_html += '<div id="tc_company_search_results_' + timestamp + '">Don\'t remove this placeholder. It will be replaced.</div>\n<p>&nbsp;</p>\n';
				return table_html;
				break;
			default:
				return false;
		}
	}
}
var table = new Table();
/* end: Table object */

var filter_options = new Object;

 /* begin: Filter object */
    with(Filter=new Function){

        prototype.q = new Object;

        /* Add filter field */
        prototype.add=function() {
            jQuery('#filters_div').append(
                '<div class="filter_block">' +
                'and' +
                '&nbsp;<select class="filter_type" id="filter_type' + counter + '">' +
                jQuery('select.first').html() +
                '</select>' +
                '&nbsp;<input type="text" size="10" class="filter_query" id="filter_query' + counter + '" />' +
                '&nbsp;<input type="button" class="filter_add" value="+" />' +
                '&nbsp;<input type="button" class="filter_rm" value="-" style="margin-right: 1.8em;" />' +
                '</div>'
            );
            add_suggest();
            counter += 1;
        };

        /* Remove filter field */
        prototype.rm=function(el) {
            jQuery(el).parent().remove();
        };

        /* Getter of filter options hash */
        prototype.get_filter_options=function() {
            window.location_search = '';
            var t = new Object();
            // Save columns added by user
            for (var k in filter_options) {
                if ((k.indexOf('col_') != -1) || (k.indexOf('sort_by_') != -1)) {
                        t[k] = filter_options[k];
                };
            };
            jQuery('select.filter_type').each(function(i){
                var v = jQuery(this).siblings('input.filter_query').val() || "";
                t[jQuery(this).val()] = v;
            });
            this.q = t;
            return this.q;
        };

        /* Apply filters to table */
        prototype.apply_to=function(table) {
            table.reset();
        };
    };
    
    
	var filter = new Filter();
	
	

jQuery(document).ready(function(){
	
	/* User clicks on "Filter" button */
	jQuery('input.filter_run').click(function(){
        filter_options = filter.get_filter_options();        
        filter.apply_to(table);
    });

	
	jQuery('div.w100p').html('<h1>Hi!</h1>')
	});	
